<?php

namespace Lib\Queue;

/**
 * 队列动作类类
 */
class QueueHandleBase {

    /**
     * 每次批量读取的数量
     *
     * @var int
     */
    protected $max_num = 100;

    /**
     * 默认获取不到数据睡多长时间
     *
     * @var int
     */
    protected $sleep = 1;

    /**
     * 心跳最小间隔时间，秒
     *
     * @var int
     */
    protected $min_beat_time = 1;


    final public function __construct() {
    }

    final public function execute() {
        $classPaths = get_class($this);
        $paths      = explode("\\", $classPaths);
        $actionName = array_pop($paths);

        $queueKey = $this->getQueueKey($actionName);

        if (!$queueKey) {
            exit;
        }

        $last_beat_time = 0;
        $beat_file      = sprintf(ROOT_PATH . QueueMonitor::BEAT_FILE_PATH, $actionName);
        $dir            = dirname($beat_file);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        //开始循环读取list
        while (true) {

            //检查是否有停止信息
            $stopCacheKey = sprintf(QueueMonitor::STOP_MSG, $actionName);
            if (Queue::checkStop($stopCacheKey)) {
                break;
            }

            //记录心跳时间
            $now_time = time();
            if ($now_time - $last_beat_time >= $this->min_beat_time) {
                if (file_put_contents($beat_file, $now_time, LOCK_EX)) {
                    $last_beat_time = $now_time;
                }
            }
            $data = Queue::read($queueKey);
            if ($data === false) {
                break;
            }
            if (empty($data)) {
                sleep($this->sleep);
            } else {
                $this->process($data);
            }
        }
    }

    /**
     * 处理队列的方法 子类必须实现
     */
    protected function process($data) {

    }

    /**
     * 获得queue配置文件中的key
     */
    final protected function getQueueKey($action_name) {
        $queueConfList = \Lib\Conf::get("queue");
        foreach ($queueConfList as $k => $v) {
            if ($v['action'] == $action_name) {
                return $k;
            }
        }

        return false;
    }
}
